package com.aiyige.utils;

import android.os.Handler;
import android.os.HandlerThread;
import android.os.Message;
import android.text.TextUtils;

/**
 * Created by zhuyakun on 2018/1/12.
 */

public class SearchHandlerWrapper {
    static final int HANDLE_SEARCH = 1;
    Handler searchHandler = null;
    HandlerThread searchThread = null;
    SearchCallback searchCallback = null;

    public SearchHandlerWrapper(String threadName) {
        searchThread = new HandlerThread(threadName);
        searchThread.start();
        searchHandler = new Handler(searchThread.getLooper()) {
            @Override
            public void handleMessage(Message msg) {
                switch (msg.what) {
                    case HANDLE_SEARCH:
                        if (searchCallback != null) {
                            searchCallback.search((String) msg.obj);
                        }
                        break;
                    default:
                        break;
                }
            }
        };
    }

    public void setSearchCallback(SearchCallback searchCallback) {
        this.searchCallback = searchCallback;
    }

    public void postSearch(String searchStr) {
        if (TextUtils.isEmpty(searchStr)) return;
        Message msg = Message.obtain();
        msg.what = HANDLE_SEARCH;
        msg.obj = searchStr;
        searchHandler.removeMessages(HANDLE_SEARCH);
        searchHandler.sendMessage(msg);
    }

    public void destroy() {
        if (searchThread != null) {
            searchThread.quit();
        }
    }

    public interface SearchCallback {
        void search(String searchStr);
    }
}
